#include <commands\server\s_send_model_description.h>
#include <app\states\modelInfoState.h>
#include <app\states\connectionState.h>
#include <app\states\cacheState.h>

#include <Poco\Path.h>
#include <Poco\File.h>

REGISTER_COMMAND(SERVER_SEND_MODEL_DESCRIPTION, s_send_model_description)

s_send_model_description::s_send_model_description() : command(0, NULL) {
  data = NULL;
  size = 0;
}

s_send_model_description::s_send_model_description(unsigned int _type_id, streamingConnection *_connection) : command(_type_id, _connection) {
  data = NULL;
  size = 0;
}

void 
s_send_model_description::setData(unsigned char *_data, int _size) {
  data = _data;
  size = _size;
}

void 
s_send_model_description::decode(stringstream &bytes_stream, int size) {
#ifdef CLIENT
  
  #ifdef DEBUG_INFO
  std::cerr << "CLIENT DECODE: s_send_model_description" << std::endl;
  #endif

  data = new unsigned char[size];
  bytes_stream.read((char *) data, size);

  streamingConnection * conn = getconnection();

  // get model info state
  modelInfoState *mfstate = GET_STATE(modelInfoState, conn);
  // load received model info
  mfstate->loadFromRawData(data, size);

  if (data) delete [] data;

  //TODO: compare received model info with current model info?

  // save received model info to file
  connectionState *cstate = GET_STATE(connectionState, conn);
  cacheState *cachestate = GET_STATE(cacheState, conn);

  Poco::Path model_dir;
  model_dir.pushDirectory(cachestate->getCacheDir().toString());
  model_dir.pushDirectory(cstate->getModelName());
  Poco::File file(Poco::Path(model_dir, cstate->getModelName() + ".def"));

  mfstate->saveInfo(file);

  mfstate->setModelInfoReceived(true);

#endif
}

void 
s_send_model_description::execute() {
#ifdef SERVER

  #ifdef DEBUG_INFO
  std::cerr << "SERVER EXECUTE: s_send_model_description" << std::endl;
  #endif

  unsigned int *id = new unsigned int[1];
  unsigned int *total_size = new unsigned int[1];

  total_size[0] = sizeof(unsigned int); // total size itself

  id[0] = getTypeId();
  total_size[0] += sizeof(unsigned int); // id size

  total_size[0] += size;

  sendBytes(total_size, sizeof(unsigned int));
  sendBytes(id, sizeof(unsigned int));

  sendBytes(data, size);

#endif
}

